<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://xxx.com/register" id="registerForm" method="post">
    请输入用户名:<input type="text" name="userName"/>
    请输入密码:<input type="text" name="password"/>
    请输入手机号码: <input type="text" name="phoneNumber">
    <button>提交</button>

</form>
<script>
  var strategies = {
      isNonEmpty:function (value, errorMsg) {
          if(value === ''){
              return errorMsg;
          }
      },
      minLength:function (value,length,errorMsg){
          if(value.length<length){
              return errorMsg;
          }
  } ,isMobile:function (value,errorMsg) {
          //!/(^1[3|5|8][0-9]{9}$)/.test( value )
              if(!/(^1[3|4|5|8][0-9]{9}$)/.test(value))   {
                  return errorMsg;
              }

      }
  };
  var validataFun = function () {
      var validata = new Validator();
      validata.add(registerForm.userName,'isNonEmpty','用户名不能为空');
      validata.add(registerForm.password,'minLength:6','密码长度不对');
      validata.add(registerForm.phoneNumber,'isMobile','手机号码不正确')
      var errorMsg = validata.start();
      return errorMsg;
  }
  var registerForm = document.getElementById('registerForm');
  registerForm.onsubmit = function () {
      var errorMsg = validataFun();
      if(errorMsg){
          alert(errorMsg);
          return false;
      }
  }
  var Validator = function () {
      this.cache = [];  // 保留规则
  }
  Validator.prototype.add = function (dom,rule,errorMsg) {
      var ary = rule.split(':');
      this.cache.push(function () {
          var strategy = ary.shift();
          ary.unshift(dom.value);
          ary.push(errorMsg);
          return strategies[strategy].apply(dom,ary)
      })
  }
  Validator.prototype.start = function () {
      for(var i = 0,validatorFun;validatorFun = this.cache[i++];){
          var msg = validatorFun();
          if(msg){
              return msg;
          }
      }
  }
</script>
</body>
</html>